<template>
  <el-dialog
    title="创建工作单位"
    :visible.sync="dialogVisible"
    width="500px"
    :close-on-click-modal="false"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="单位名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入公司名称" />
      </el-form-item>
      <el-form-item label="单位Logo" prop="logo">
        <el-upload
          class="logo-uploader"
          action="/api/v1/upload/file"
          :show-file-list="false"
          :on-success="handleLogoSuccess"
          :before-upload="beforeLogoUpload"
        >
          <img v-if="form.logo" :src="form.logo" class="logo">
          <i v-else class="el-icon-plus logo-uploader-icon" />
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'CompanyCardCreate',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // visible: false,
      form: {
        name: '',
        logo: ''
      },
      rules: {
        name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }]
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(v) {
        this.$emit('update:visible', v)
      }
    }
  },
  methods: {
    handleLogoSuccess(res) {
      this.form.logo = res.data.path
    },
    beforeLogoUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传Logo只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传Logo图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$emit('submit', this.form)
          this.close()
        }
      })
    },
    close() {
      this.$emit('update:visible', false)
      this.form = this.$options.data().form
      this.$refs.form.clearValidate()
    }
  }
}
</script>

<style lang="scss" scoped>
.logo-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409EFF;
    }
  }
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.logo {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
